package com.ahs.algorithm;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author riven zhang
 * @since 2021/9/1 13:36
 * 统计素数的个数 - 埃氏筛选
 */
public class PrimeNumber {

    /**
     * 埃氏筛选法 复杂度n*lgN
     */
    private List<Integer> aiFilter(int num) {
        boolean[] isPrime = new boolean[num];
        int count = 0;
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 2; i < num; i++) {
            if (!isPrime[i]) {
                list.add(i);
                count++;
                for (int j = 2 * i; j < num; j += i) {
                    isPrime[j] = true;
                }
            }
        }
        return list;
    }

    /**
     * 暴力计算法，复杂度n*n
     */
    private List<Integer> violenceCount(int num) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 2; i < num; i++) {
            if (isPrime(i)) {
                list.add(i);
            }
        }
        return list;
    }

    private boolean isPrime(int num) {
        for (int i = 2; i < num; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }

    @Test
    void test() {
        System.out.println(aiFilter(100));
        System.out.println(violenceCount(100));
    }
}
